﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.Timers;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{

    public partial class ApplicationBase : INotifyPropertyChanged
    {
        public string INFO = "";
        public string[] WA = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        private string _OSV = "";
        public string OSV
        {
            get
            {
                if (_OSV == "")
                {
                    System.OperatingSystem osInfo = System.Environment.OSVersion;
                    System.PlatformID platformID = osInfo.Platform;
                    int versionMajor = osInfo.Version.Major;
                    int versionMinor = osInfo.Version.Minor;
                    _OSV = versionMajor.ToString();
                    if (versionMajor >= 6)
                        IsXP = false;
                    else
                    {
                        IsXP = true;
                    }
                }
                return _OSV;
            }
        }
        public bool IsXP
        {
            get;
            set;
        }
        public static readonly ApplicationBase Instance = new ApplicationBase();
        public void Load(bool IsDrectly = false)
        {
            if (!IsDrectly)
            {
                Load();
            }
            else
            {
                LoadOnServer();
            }

        }
        public void LoadOnServer()
        {
            try
            {
                if (IsLoaded)
                    return;
                INFO = "";
                INFO += "开始装载";
                IsHelp = false;
                IsTranslate = false;
                ReadConfig(ref EnvExe);
                EnvExe["m_log_out"] = m_log_out;
                INFO += "开始装载proxy";
                EnvExe["proxy"] = proxy;
                INFO += "开始装载proxy";
                Connect2DB(INTEXSYS, DBUSER, DBPWD);
                //OracleDB.ConnectionString=OracleDB.ConnectionString.Replace("intex2", "intex1");
                INTEXDBC = new INTEXDBC(OracleDB, proxy);
                INTEXDBC.UserID = User;
                INFO += "开始装载INTEXDBC";
                INTEXBL = new INTEXBL();
                INTEXBL.OracleDB = OracleDB;
                INTEXBL.proxy = proxy;
                IsLoaded = true;
                Connected = true;
                if (IsKeepOnLine)
                {
                    OnLineTimer = new Timer();
                    OnLineTimer.Interval = 1000 * 60 * 5;
                    OnLineTimer.Elapsed += OnLineTimer_Elapsed;
                    OnLineTimer.Start();
                }
            }
            catch (Exception ex)
            {
                INFO += ex.StackTrace + ex.Message;
                IsOnline = false;
            }
            finally
            {
                if (Connected)
                {
                    Tracer.Info("登陆", "登录成功");
                }
                else
                {
                    Tracer.Info("登陆", "登录失败");
                }
            }

        }
        public void Load()
        {

            try
            {
                if (IsLoaded)
                    return;
                INFO = OSV;
                INFO += "开始装载";
                IsHelp = false;
                IsTranslate = false;
                IsSingleRun = false;
                IsSQLDEMO = false;
                IsWFMSG = false;
                 IsMenuTree = false;
                ReadConfig(ref EnvExe);
                if (SingleRun == "1")
                    IsSingleRun = true;
                if (SQLDEMO == "1")
                    IsSQLDEMO = true;
                if (MENUTREE == "1")
                    IsMenuTree = true;
                if (WFMSG == "1")
                    IsWFMSG = true;
                
                EnvExe["m_log_out"] = m_log_out;
                INFO += "开始装载proxy";
                EnvExe["proxy"] = proxy;
                INFO += "开始装载proxy";
                Connect2DB(INTEXSYS, DBUSER, DBPWD);
                //OracleDB.ConnectionString=OracleDB.ConnectionString.Replace("intex2", "intex1");
                INTEXDBC = new INTEXDBC(OracleDB, proxy);
                INTEXDBC.UserID = User;
                INFO += "开始装载INTEXDBC";
                INTEXBL = new INTEXBL();
                INTEXBL.OracleDB = OracleDB;
                INTEXBL.proxy = proxy;
                Connected = GetID();
                INFO += "开始装载Connected";
                if (!Connected)
                {
                    INFO = "登陆失败,授权有效期:" + LicenseDate + ",授权用户:" + license + ",在线用户" + itxonline;
                    throw new Exception(INFO);
                }

                INTEXDB.Merge(LoadSetSETUP(company, User));
                if (INTEXDB.Tables.Contains("ICC_HRSTAMM"))
                {
                    if (INTEXDB.Tables["ICC_HRSTAMM"].Rows.Count > 0)
                    {
                        DataRow dwUser = INTEXDB.Tables["ICC_HRSTAMM"].Rows[0];
                        EnvExe["ExcelFile"] = Path.Combine(PathHelper.ApplicationPath, @"Report\" + company + "\\" + dwUser["EXCELFILE"].ToString().Trim());
                    }
                }
                if (EnvExe.ContainsKey("CHECKFOLDER"))
                {
                    CHECKFOLDER = (string)EnvExe["CHECKFOLDER"];
                }
                if (INTEXDB.Tables.Contains(company + "USERRIGHT"))
                {
                    EnvExe["USERRIGHT"] = INTEXDB.Tables[company + "USERRIGHT"];
                }
                EnvExe["ExcelFile"] = Path.Combine(PathHelper.ApplicationPath, @"Report\" + company + "\\" + EnvExe["ExcelFile"].ToString().Trim());
                //INTEXDBC.OracleDB.ConnectionString = OracleDB.ConnectionString.Replace("intex1", INTEXSYS);
                //INTEXBL.OracleDB.ConnectionString = OracleDB.ConnectionString.Replace("intex1", INTEXSYS);
                if (IsKeepOnLine)
                {
                    OnLineTimer = new Timer();
                    OnLineTimer.Interval = 1000 * 60 * 5;
                    OnLineTimer.Elapsed += OnLineTimer_Elapsed;
                    OnLineTimer.Start();
                }
                IsLoaded = true;
                INTEXBL.ZLANSTART();
                INTEXBL.SignalRSTART();
            }
            catch (Exception ex)
            {
                INFO += ex.StackTrace + ex.Message;
                IsOnline = false;
            }
            finally
            {
                if (Connected)
                {
                    Tracer.Info("登陆", "登录成功");
                }
                else
                {
                    Tracer.Error("登陆", "登录失败");
                }
            }

        }
        private void ReadConfig(ref Dictionary<string, object> env)
        {
            string key = "";
            string value = "";

            bool Found = false;
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            for (int i = 0; i < appSettings.Count; i++)
            {
                key = appSettings.GetKey(i);
                if (key == "ServiceUri")
                {
                    Found = true;
                }
                value = appSettings[i];
                if (env.ContainsKey(key))
                {
                    env[key] = value;
                }
                else
                {
                    env.Add(key, value);
                }
            }
            if (!Found)
            {
                CreateAppSettings();
            }
            if (!env.ContainsKey("blBuildCellMastrix"))
            {
                env.Add("blBuildCellMastrix", false);
            }
            if (!env.ContainsKey("_Control"))
            {
                env.Add("_Control", this);
            }
            if (!env.ContainsKey("dsParamaters"))
            {
                env.Add("dsParamaters", null);
            }
            if (!env.ContainsKey("ExCelNameMatrix"))
            {
                env.Add("ExCelNameMatrix", null);

            }
            if (!env.ContainsKey("USERRIGHT"))
            {
                env.Add("USERRIGHT", null);

            }
            if (!env.ContainsKey("ApplicationBase"))
            {
                env.Add("ApplicationBase", this);

            }
            if (!env.ContainsKey("ActiveDocument"))
            {
                env.Add("ActiveDocument", null);
            }
            if (!env.ContainsKey("LANG"))
            {
                env.Add("LANG", "V");
            }
        }
        #region==============INotifyPropertyChanged===============
        public object Tag;
        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged(string propertyName, object value)
        {
            this.Tag = value;
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        public Dictionary<string, object> ENVMAIN(string ip)
        {

            if (!EnvExe.ContainsKey(ip))
            {
                EnvExe[ip] = new Dictionary<string, object>();
                ((Dictionary<string, object>)EnvExe[ip])["IsLogOn"] = false;
                ((Dictionary<string, object>)EnvExe[ip])["IsLoaded"] = false;
                ((Dictionary<string, object>)EnvExe[ip])["INTEXDBC"] = null;
            }
            return (Dictionary<string, object>)EnvExe[ip];
        }
        public bool IsLogOn
        {
            get
            {
                return (bool)ENVMAIN(UserIP)["IsLogOn"];
            }
            set
            {
                ENVMAIN(UserIP)["IsLogOn"] = value;
            }
        }
        ITXConnectInfo _itxclient;
        public ITXConnectInfo itxclient
        {
            get
            {
                if (_itxclient == null)
                {
                    _itxclient = new ITXConnectInfo();
                    _itxclient.Server = itxsrv;
                    _itxclient.Port = itxport; 
                }
                return _itxclient;
            }
        }
        public int itxport
        {
            get
            {
                if (EnvExe.ContainsKey("itxport"))
                {
                    return int.Parse(EnvExe["itxport"].ToString());
                }
                else
                {
                    return 25002;
                }
            }
        }
        public string itxsrv
        {
            get
            {
                if (EnvExe.ContainsKey("itxsrv"))
                {
                    return (string)EnvExe["itxsrv"];
                }
                else
                {
                    return "127.0.0.1";
                }
            }
        }

        public bool IsLoaded
        {
            get
            {
                return (bool)ENVMAIN(UserIP)["IsLoaded"];
            }
            set
            {
                ENVMAIN(UserIP)["IsLoaded"] = value;
            }
        }
        private string _UserIP = "";
        public string UserIP
        {
            get
            {
                if (_UserIP == "")
                    _UserIP = GetIp();
                return _UserIP;
            }
            set
            {
                _UserIP = value;
            }
        }
        private string _AppMode = "";
        public string AppMode
        {
            get { return _AppMode; }
            set
            {
                _AppMode = value;
                OnPropertyChanged("AppMode", value);
            }
        }
        private string _WAEHRSL = "";
        public string WAEHRSL
        {
            get { return _WAEHRSL; }
            set
            {
                _WAEHRSL = value;
                OnPropertyChanged("WAEHRSL", value);
            }
        }
        public DataTable TBPRG
        {
            get;
            set;
        }
        public DataTable TBUR
        {
            get;
            set;
        }
        public Dictionary<string, DataTable> DBSDDAT
        {
            get;
            set;
        }

        private string _IsBusy; public string IsBusy { get { return _IsBusy; } set { _IsBusy = value; OnPropertyChanged("IsBusy", value); } }
        private bool _IsMaster; public bool IsMaster { get { return _IsMaster; } set { _IsMaster = value; OnPropertyChanged("IsMaster", value); } }
        private bool _IsEditor; public bool IsEditor { get { return _IsEditor; } set { _IsEditor = value; OnPropertyChanged("IsEditor", value); } }
        private bool _IsViewer; public bool IsViewer { get { return _IsViewer; } set { _IsViewer = value; OnPropertyChanged("IsViewer", value); } }
        private bool _IsITX = false; public bool IsITX { get { return _IsITX; } set { _IsITX = value; OnPropertyChanged("IsITX", value); } }

        public bool IsOnline { get; set; }

        public bool IsKeepOnLine = true;

        Timer OnLineTimer;

        private bool _STA;

        public bool IsSTA
        {
            get
            {
                return _STA;
            }
            set
            {
                _STA = value;
                EventDispatcher.Instance.IsSTA = value;
            }
        }
        public bool IsWFMSG
        {
            get;
            set;
        }
        
        public bool IsSQLDEMO
        {
            get;
            set;
        }
        private bool _IsSingleRun;
        public bool IsSingleRun
        {
            get
            {
                return _IsSingleRun;
            }
            set
            {
                _IsSingleRun = value;
            }
        }
        public bool IsMenuTree
        {
            get;
            set;
        }

        public int count = 0;

        public ApplicationBase()
        {
            Connected = false;
            IsSTA = true;
            myHashtable = CheckExcellProcesses();
            KillExcel(myHashtable);
            count++;
            DBSDDAT = new Dictionary<string, DataTable>();
        }

        public string AgentID
        {
            get
            {
                return proxy.AgentID;
            }
        }

        public bool Connected
        {
            get;
            set;
        }

        public bool IsHelp
        {
            get;
            set;
        }

        public bool IsTranslate
        {
            get;
            set;
        }

        public void Quit()
        {
            try
            {
                if (!Connected)
                    return;
                Dictionary<string, object> a = new Dictionary<string, object>();
                a.Add("QAGENT", proxy.AgentID);
                DataSet SResult = proxy.RequestAgentStart(a);
                if (SResult.Tables.Count == 0) return;
                foreach (DataRow row in SResult.Tables[0].Rows)
                {

                }
            }
            catch (Exception ex)
            { }
        }

        ~ApplicationBase()
        {
            if (proxy.State != System.ServiceModel.CommunicationState.Closed)
            {
                proxy.Close();
            }
        }

        public log4net.ILog m_log_out = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public Dictionary<string, object> EnvExe = new Dictionary<string, object>();

        public Dictionary<string, object> dicParamater
        {
            get
            {
                return EnvExe;
            }
        }

        public OracleConnection OracleDB
        {
            get;
            set;
        }
        //proxy = new IntexReptServBLClient();

        public IntexReptServBLClient AttemptToConnect()
        {
            // this whole process needs to be thread safe
            IntexReptServBLClient _proxy = null;
            try
            {
                _proxy = new IntexReptServBLClient("bindings");
                _proxy.Open();
            }
            catch (EndpointNotFoundException ex)
            {
                Tracer.Error(ex.StackTrace, ex);

            }
            catch (TimeoutException ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                // do something here (log, show user message etc.)

            }
            return _proxy;
        }

        public IntexReptServBLClient proxy
        {
            get
            {
                if (!ENVMAIN(UserIP).ContainsKey("proxy"))
                {
                    ENVMAIN(UserIP)["proxy"] = AttemptToConnect();
                }
                if (ENVMAIN(UserIP)["proxy"] == null)
                {
                    ENVMAIN(UserIP)["proxy"] = AttemptToConnect();
                }
                return (IntexReptServBLClient)ENVMAIN(UserIP)["proxy"];
            }
            set
            {
                ENVMAIN(UserIP)["proxy"] = value;
            }
        }

        public INTEXDBC INTEXDBC
        {
            get
            {
                return (INTEXDBC)(ENVMAIN(UserIP)["INTEXDBC"]);
            }
            set
            {
                ENVMAIN(UserIP)["INTEXDBC"] = value;
            }
        }

        public INTEXBL INTEXBL
        {
            get
            {
                return (INTEXBL)ENVMAIN(UserIP)["INTEXBL"];
            }
            set
            {
                ENVMAIN(UserIP)["INTEXBL"] = value;
            }
        }

        public ITXDB INTEXDB = new ITXDB();

        public string Updater
        {
            get
            {
                return (string)EnvExe["Updater"];
            }

        }

        public DataTable UserTable
        {
            get
            {
                return INTEXDB.Tables["ICC_MENUDEF"];
            }
        }

        public string company
        {
            get
            {
                return (string)EnvExe["Company"];
            }
        }
        public string ServiceUri
        {
            get
            {
                if (EnvExe.ContainsKey("ServiceUri"))
                {
                    return (string)EnvExe["ServiceUri"];
                }
                else
                {
                    return "127.0.0.1";
                }
            }
        }
        public IPAddress SockeSerIP
        {
            get
            {
                if (!EnvExe.ContainsKey("SockeSerIP"))
                {
                    EnvExe["SockeSerIP"] = IPAddress.Parse(ServiceUri);
                }
                return (IPAddress)EnvExe["SockeSerIP"];
            }
        }


        public string INTEXSYS
        {
            get
            {
                return (string)EnvExe["dbSystem"];
            }
        }

        public string DBUSER
        {
            get
            {
                return (string)EnvExe["dbUser"];
            }
        }

        public string DBPWD
        {
            get
            {
                return (string)EnvExe["dbPwd"];
            }
        }

        public string SQLDB
        {
            get
            {
                return (string)EnvExe["SqlDB"];
            }
        }
        public string SQLITEDB
        {
            get
            {
                return (string)EnvExe["SQLITEDB"];
            }
        }

        public string LANG
        {
            get
            {
                return (string)EnvExe["LANG"];
            }
            set
            {
                EnvExe["LANG"] = value;
            }
        }

        string CHECKFOLDER = "NO";

        public string SqlDB
        {
            get
            {
                return (string)EnvExe["SqlDB"];
            }
        }
        public string ROOTDRIVE
        {
            get
            {
                return (string)EnvExe["ROOTDRIVE"];
            }
        }
        public string SubFolders
        {
            get
            {
                return (string)EnvExe["SubFolders"];
            }
        }
        public string DocType
        {
            get
            {
                return (string)EnvExe["DocType"];
            }
        }
        public string User
        {
            get
            {
                return Helper.Left(((string)EnvExe["User"]).PadRight(8), 8);
            }
            set
            {
                EnvExe["User"] = value;
            }
        }
        public string SingleRun
        {
            get
            {
                if (!EnvExe.ContainsKey("SingleRun"))
                {
                    return "0";
                }
                return Helper.Left(((string)EnvExe["SingleRun"]).PadRight(1), 1);
            }
            set
            {
                EnvExe["SingleRun"] = value;
            }
        }
        public string MENUTREE
        {
            get
            {
                if (!EnvExe.ContainsKey("MENUTREE"))
                {
                    return "0";
                }
                return Helper.Left(((string)EnvExe["MENUTREE"]).PadRight(1), 1);
            }
            set
            {
                EnvExe["MENUTREE"] = value;
            }
        }
        public string WFMSG
        {
            get
            {
                if (!EnvExe.ContainsKey("WFMSG"))
                {
                    return "0";
                }
                return Helper.Left(((string)EnvExe["WFMSG"]).PadRight(1), 1);
            }
            set
            {
                EnvExe["WFMSG"] = value;
            }
        }
        
        public string SQLDEMO
        {
            get
            {
                if (!EnvExe.ContainsKey("SQLDEMO"))
                {
                    return "0";
                }
                return Helper.Left(((string)EnvExe["SQLDEMO"]).PadRight(1), 1);
            }
            set
            {
                EnvExe["SQLDEMO"] = value;
            }
        }
        public string TERMNO
        {
            get
            {
                string termno = "";
                if (EnvExe.ContainsKey("TERMNO"))
                {
                    termno = Helper.Left(((string)EnvExe["TERMNO"]).PadRight(7), 7);
                }
                else
                {
                    termno = User;
                }
                return termno;
            }
        }
        public bool BYAGENT
        {
            get
            {
                if (EnvExe.ContainsKey("BYAGENT"))
                {
                    if ((string)EnvExe["BYAGENT"] == "NO")
                        return false;
                }
                return true;
            }
        }
        public Dictionary<string, object> UserList
        {
            get
            {
                if (!EnvExe.ContainsKey("UserList"))
                {
                    EnvExe["UserList"] = new Dictionary<string, object>();
                }
                return (Dictionary<string, object>)EnvExe["UserList"];
            }
        }
        public string Pwd
        {
            get
            {
                return (string)EnvExe["Pwd"];
            }
        }
        public string Mandant
        {
            get
            {
                return (string)EnvExe["MANDANT"];
            }
            set
            {
                EnvExe["MANDANT"] = value;
            }
        }
        Hashtable myHashtable;
        public string ApplicationPath
        {
            get { return System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath); }
        }

        public string lib
        {
            get { return System.IO.Directory.GetParent(ApplicationPath) + "\\Lib"; }
        }

        public string LayoutFile
        {
            get { return System.IO.Path.Combine(ApplicationPath, "IntexReportClient.Layout.xml"); }
        }

        public void CheckConnection()
        {
            Connected = GetID();
        }
        public int license = 9999;
        public int reportusers = 0;
        public int itxonline = 0;
        public string LicenseDate = "0"; 
        public bool GetID()
        {
            /*
            ITXClient = new ITXClient();
            ITXClient.SockeSerIP = SockeSerIP;
            ITXClient.ServicePort = 25003;
            ITXClient.LocalIP = UserIP;
            ITXClient.Connect();*/
            bool IsSuccess = true;
            proxy.BYAGENT = BYAGENT;
            Dictionary<string, object> pm = new Dictionary<string, object>();
            pm.Add("CommandType", "SAGENT");
            DataSet SResult = proxy.RequestAgentStart(pm);
            if (SResult.Tables.Count == 0)
            {
                IsSuccess = false;
                return IsSuccess;
            }
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                proxy.AgentID = row["AGENTID"].ToString();
                DataRow dwData = INTEXDB.ICC_QUERYTB.NewRow();
                dwData["HRMANDANT"] = Mandant;
                DataSet SetUser = INTEXDBC.QueryHRSTAMM(dwData, 5);

                bool IsExpired = false;
                string date = "",time="",stime="";
                Helper.GetSTime(ref date, ref time, ref stime);
                foreach (DataRow rhr in SetUser.Tables[0].Rows)
                {
                    string ls = rhr["HRDTELD"].ToString();
                    LicenseDate = rhr["HRFILLER"].ToString().Trim();
                    if(LicenseDate == "")
                    {
                        IsExpired = false;
                    }
                    else
                    {
                        if (double.Parse(LicenseDate) < double.Parse(date))
                            IsExpired = true;
                    }
                    if(IsExpired)
                    {
                        IsSuccess = false;
                        Tracer.Info("ApplicationBase.AgentID", "软件有效期至:"+ LicenseDate);
                        return IsSuccess;

                    }
                    if (ls.Trim() == "")
                        license = 0;
                    else
                    {
                        license = Convert.ToInt16(ls);
                    }
                    if (license == 0)
                    {
                        license = 9999;
                    }
                    string on = rhr["DB11"].ToString();
                    if (on.Trim() == "")
                        itxonline = 0;
                    else
                    {
                        itxonline = Convert.ToInt16(on);
                    }
                }
                if (SResult.Tables[0].Columns.Contains("USERS"))
                {
                    reportusers = Convert.ToInt16(row["USERS"].ToString());
                    if (license - (reportusers + itxonline) > -1)
                    {
                        proxy.AgentID = row["AGENTID"].ToString();
                        Tracer.Info("AgentID" + proxy.AgentID + ",intex 用户:" + itxonline + "，用户：" + reportusers, ",申请成功");
                    }
                    else
                    {
                        IsSuccess = false;
                        Tracer.Info("ApplicationBase.AgentID", "申请不成功:");
                        return IsSuccess;
                    }
                }
            }
            IsOnline = IsSuccess;
            return IsSuccess;
        }


        void OnLineTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                DataRow dwData = INTEXDB.ICC_QUERYTB.NewRow();
                dwData["MANDANT"] = Mandant;
                dwData["COMPANY"] = company;
                INTEXDBC.QueryICC_HRSTAMM(dwData, 3);
            }
            catch (Exception ex)
            {
            }
        }

        private void Connect2DB(string intex, string dbuser, string dbpwd)
        {
            string OracleDBConnString = "user id=" + dbuser
                    + ";data source=" + intex
                    + ";password=" + dbpwd + ";Unicode=True;"
                       + "Persist Security Info=True;";
            if (OracleDB != null)
            {
                OracleDB.Close();
            }
            OracleDB = new OracleConnection(OracleDBConnString);
            OracleDB.ConnectionString = OracleDBConnString;
            EnvExe["OracleDB"] = OracleDB;
            EnvExe["OracleDBConnString"] = OracleDBConnString;
            SqlConnection SqlServerDB = new SqlConnection(SQLDB);
            EnvExe["SqlServerDB"] = SqlServerDB;
            EnvExe["SqlServerDBConnString"] = SQLDB;
        }


        // Create the AppSettings section.
        // The function uses the GetSection(string)method 
        // to access the configuration section. 
        // It also adds a new element to the section collection.
        public void CreateAppSettings()
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
              ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);
            string newKey = "ServiceUri";
            string newValue = "180.166.130.110";
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
            //config.AppSettings.Settings.Remove(); 
            ConfigurationManager.RefreshSection("appSettings");

        }

        public void ChgAppSettings(string key, string value)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
              ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            appSettings[key] = value;
            config.Save(ConfigurationSaveMode.Modified);
            //config.AppSettings.Settings.Remove(); 
            ConfigurationManager.RefreshSection("appSettings");
        }

        public Hashtable CheckExcellProcesses()
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");
            Hashtable myHashtable = new Hashtable();
            int iCount = 0;

            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
            return myHashtable;
        }

        public void KillExcel(Hashtable myHashtable)
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");

            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }

            AllProcesses = null;
        }

        public DataSet ReSetSETUP()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataSet settemp = new DataSet();
            DataSet SResult = LoadSetSETUP(company, User);
            INTEXDB.Merge(SResult);
            return setReturn;
        }

        public DataSet LoadSetSETUP(string company, string user)
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            DataRow dwData = null;
            if (!Connected)
            {
                return setReturn;
            }
            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["MANDANT"] = Mandant;
            dwData["COMPANY"] = company;
            dwData["USERID"] = Helper.Left(User + "    ", 8);
            setResult = INTEXDBC.QueryICC_HRSTAMM(dwData, 2);
            setReturn.Merge(setResult);

            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["MANDANT"] = Mandant;
            dwData["COMPANY"] = company;
            dwData["USERID"] = Helper.Left(User + "    ", 8);

            setResult = INTEXDBC.QueryICC_MENUDEF(dwData, 2);
            setReturn.Merge(setResult);
            if (CHECKFOLDER == "YES")
            {
                dwData = INTEXDB.ICC_QUERYTB.NewRow();
                dwData["MANDANT"] = Mandant;
                setResult = INTEXDBC.QueryICC_FOLDERS(dwData, 9999);
                foreach (DataRow rowf in setResult.Tables[0].Rows)
                {
                    Helper.CheckDirectory(rowf["ROOT"].ToString(), rowf["SUB"].ToString());
                }
            }
            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["HRMANDANT"] = Mandant;
            dwData["HRBENID"] = Helper.Left(User + "    ", 8);
            setResult = INTEXDBC.QueryHRSTAMM(dwData, 2);
            setReturn.Merge(setResult);
            IsTranslate = false;
            if (setResult.Tables.Count > 0)
            {
                foreach (DataRow row in setResult.Tables[0].Rows)
                {
                    if (row["HRSPRKZ"].ToString().Trim() == "E")
                    {
                        LANG = "EN";
                        IsTranslate = true;
                    }
                }
            }
            return setReturn;
        }

        public DataRow UserValid(string name, string pwd)
        {
            if (!INTEXDB.Tables.Contains("ICC_HRSTAMM"))
                return null;
            string filter = " TRIM(USERID) ='" + name.ToUpper().Trim() + "' AND TRIM(PWD)='" + pwd.ToUpper().Trim() + "'";
            DataRow[] rows = INTEXDB.Tables["ICC_HRSTAMM"].Select(filter);
            if (rows.Length > 0)
                return rows[0];
            else
                return null;
        }

        public DataRow GetUser(string name)
        {
            if (!INTEXDB.Tables.Contains("HRSTAMM"))
                return null;
            string filter = "HRBENID ='" + Helper.Left(name.PadRight(8), 8) + "'";
            DataRow[] rows = INTEXDB.Tables["HRSTAMM"].Select(filter);
            if (rows.Length > 0)
                return rows[0];
            else
                return null;
        }
        public SortedDictionary<string, string> SDC;
        public void PrepareMulLang()
        {
            if (LANG == "V")
                return;
            SDC = new SortedDictionary<string, string>();
            OracleCommand or1 = OracleDB.CreateCommand();
            or1.CommandText = "SELECT * FROM ICC_MULLANG WHERE MANDANT='" + Mandant + "'";
            DataSet SResult = INTEXDBC.Connect2Proxy(or1);
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                string key = Helper.GetGB2312Value(row["MLKEY"].ToString().Trim());
                SDC[key] = Helper.GetGB2312Value(row["EN"].ToString().Trim());
            }
        }
        public string StartTranslate(string key)
        {
            if (!IsTranslate)
                return key;
            if (!SDC.ContainsKey(key))
                return key;
            return SDC[key];
        }

        public string GetIp()
        {
            string hostname = "";
            IPHostEntry localhost;
            IPAddress localaddr = null;
            try
            {
                hostname = Dns.GetHostName();//得到本机名  
                localhost = Dns.GetHostEntry(hostname);
                localaddr = localhost.AddressList[0];
            }
            catch (Exception ex)
            {
            }
            return localaddr.ToString();
        }

        public void LogOn()
        {
            if (User.Trim() == "ITXV")
            {
                IsITX = true;
            }
        }
    }
}